<template>
    <!-- 在页面顶部或底部添加加载遮罩 -->
    <div v-loading="submitting" class="inventory-detail-container">
        <div class="inventory-detail-container">
            <!-- Document Information Group -->
            <el-card class="info-card" shadow="never">
                <template #header>
                    <div class="card-header">
                        <div class="title-wrapper">
                            <span class="title-text">单据信息</span>
                            <span class="store-name">{{ inventory.storeName }}</span>
                            <el-tag v-if="!this.editMode"
                                :type="inventory.status.code === CommonOrderStatus.Passed.code ? 'success' : 'info'"
                                size="small" class="status-tag">
                                {{ inventory.status.name }}
                            </el-tag>
                        </div>
                        <!-- Action Buttons -->
                        <div class="action-buttons" v-if="!this.editMode">
                            <el-button plain @click="handleCopy">
                                <el-icon>
                                    <CopyDocument />
                                </el-icon> 复制
                            </el-button>
                            <el-button plain @click="handlePrint" style="margin-right: 20px">
                                <el-icon>
                                    <Printer />
                                </el-icon> 打印
                            </el-button>
                            <el-button type="primary" plain @click="handleEdit">
                                <el-icon>
                                    <Edit />
                                </el-icon> 编辑
                            </el-button>
                            <el-button type="danger" plain @click="handleDelete">
                                <el-icon>
                                    <Delete />
                                </el-icon> 删除
                            </el-button>
                        </div>

                    </div>
                </template>
                <el-form ref="ruleFormRef" :model="formData" label-width="100px">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <input-widget-web v-model="formData.title" label="单据标题" prop="title"
                                :readonly="!this.editMode" />
                        </el-col>
                        <el-col v-if="!this.editMode" :span="6">
                            <input-widget-web v-model="formData.docCode" label="单据编号" prop="docCode"
                                :readonly="!this.editMode" />
                        </el-col>


                        <!-- 注意下面这些控件均没有监听@change 所以数据变化全部都在formData中 -->
                        <el-col :span="6">
                            <partner-select v-model="formData.targetObject" label="往来单位" prop="targetObject"
                                :readonly="!this.editMode" :initialPartnerType="initPartnerCode"
                                :rules="[{ required: true, message: '请选择往来单位', trigger: 'blur' }]"
                                :basicUiAction="basicUiAction" />
                        </el-col>
                        <el-col :span="6">
                            <inventory-type-select v-model="formData.inventoryType" :label="inoutTypeLabel"
                                prop="inventoryType" :readonly="!this.editMode" :inventoryUiAction="inventoryUiAction"
                                :inOutType="inOutType" />
                        </el-col>
                        <el-col :span="6">
                            <warehouse-select v-model="formData.warehouse" label="仓库" prop="warehouse"
                                :readonly="!this.editMode" :inventoryUiAction="inventoryUiAction" />
                        </el-col>

                        <el-col :span="6">
                            <date-time-select v-model="formData.operateDate" :label="operationTimeLabel"
                                prop="operateDate" :readonly="!this.editMode" type="datetime" />
                        </el-col>

                        <!--
                    <el-col :span="6">
                        <input-widget-web v-model="formData.operator" label="经办人" prop="operator"
                            :readonly="!this.editMode" />
                    </el-col>
                    -->

                        <el-col :span="6">
                            <employee-select v-model="formData.operator" label="经办人" prop="operator"
                                :readonly="!this.editMode" :enterpriseMgtUiAction="enterpriseMgtUiAction" />
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>

            <!-- Inventory Items Group -->
            <el-card class="items-card" shadow="never">
                <template #header>
                    <div class="card-header">
                        <div class="title-wrapper">
                            <div class="summary-container">
                                <span class="title-text">{{ commodityGroupTitle }}</span>
                                <span class="total-info">
                                    共{{ inventory.totalCount.value }}件，合计{{ inventory.inventoryFundMount.value }}元
                                </span>
                            </div>
                            <!-- 添加和删除按钮 -->
                            <div v-if="editMode" class="action-buttons">
                                <el-button type="primary" size="small" @click="handleAddCommodity">
                                    添加商品
                                </el-button>
                                <el-button type="danger" size="small" @click="handleDeleteSelectedCommodities">
                                    删除商品
                                </el-button>
                            </div>
                        </div>
                    </div>
                </template>

                <el-table :data="inventory.commmodityList" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <!-- 勾选列 -->
                    <el-table-column type="selection" width="55" v-if="editMode" />
                    <el-table-column label="图片" width="150">
                        <template #default="scope">
                            <el-image v-if="scope.row.commodity.imgs" :src="scope.row.commodity.imgs.split(',')[0]"
                                fit="cover" class="commodity-image"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品名称" width="180">
                        <template #default="scope">
                            {{ scope.row.commodity.name }}
                        </template>
                    </el-table-column>
                    <el-table-column label="规格" width="180">
                        <template #default="scope">
                            {{ scope.row.commodity.standard }}
                        </template>
                    </el-table-column>
                    <el-table-column label="单位" width="80">
                        <template #default="scope">
                            {{ scope.row.commodity.unit?.name || '-' }}
                        </template>
                    </el-table-column>

                    <el-table-column label="单价" align="right" width="100">
                        <template #default="scope">
                            <single-price-input-cell v-if="editMode" :commodityBatch="scope.row" />
                            <span v-else>{{ formatCurrency(scope.row.singlePrice.value) }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="数量" align="right" width="100">
                        <template #default="scope">
                            <quality-input-cell v-if="editMode" :commodityBatch="scope.row" :decimalAllowed="true" />
                            <span v-else>{{ formatCount(scope.row.count.value) }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="金额" align="right" width="100">
                        <template #default="scope">
                            <total-price-input-cell v-if="editMode" :commodityBatch="scope.row" />
                            <span v-else>{{ formatCurrency(scope.row.batchPrice.value) }}</span>
                        </template>
                    </el-table-column>

                </el-table>
            </el-card>

            <!-- Other Information Group -->
            <el-card class="other-info-card" shadow="never">
                <template #header>
                    <div class="card-header">
                        <span class="title-text">其他信息</span>
                    </div>
                </template>

                <el-descriptions v-if="!editMode" :column="1">
                    <el-descriptions-item v-if="latestUpdateInfo" label="最近更新">{{ latestUpdateInfo
                        }}</el-descriptions-item>
                    <el-descriptions-item label="制单人">{{ docMaker }}</el-descriptions-item>
                    <el-descriptions-item label="备注">
                        <div class="remark-content">{{ inventory.remark || '-' }}</div>

                    </el-descriptions-item>
                </el-descriptions>

                <!-- 备注 -->
                <input-widget-web v-if="editMode" v-model="formData.remark" label="备注" prop="remark"
                    placeholder="请输入备注信息" :remarkMode="true" />


            </el-card>

            <!-- 底部操作栏 (仅在编辑模式下显示) -->
            <bottom-bar :visible="editMode">
                <template #left>
                    <span class="doc-maker-info">制单人: {{ docMakerBottmBar }}</span>
                </template>
                <template #right>
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">提交</el-button>
                </template>
            </bottom-bar>
            <!-- 商品选择弹窗 -->
            <subcommodity-select-dialog ref="commoditySelectDialog" :basic-ui-action="basicUiAction"
                @select="handleCommoditySelect" />
        </div>
    </div>
</template>

<script>
import { Inventory, InventoryInOutType, CommodityBatch } from '../../public/engine/inventory/inventory'
import { Employee } from '../../public/engine/enterpriseMgt/employee'
import { CsDouble } from '../../public/engine/common/csDouble'
import { CommonOrderStatus } from '../../public/engine/common/docDefinition'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction'
import { Util } from '../../public/utils/util'
import { DateUtil } from '../../public/utils/dateUtil'
import { Engine } from '../../public/engine/engine'
import { ElMessage, ElMessageBox } from 'element-plus'
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction'
import { EnterpriseMgtUiAction } from '../../public/engine/uiAction/enterpriseMgtUiAction.js'
import { ActionResult, ActionResultType } from '../../public/engine/common/actionResult.js'
import InputWidgetWeb from '../../public/views/componentsWeb/InputWidgetWeb.vue'
import PartnerSelect from '../../public/views/componentsWeb/PartnerSelect.vue'
import InventoryTypeSelect from '../../public/views/componentsWeb/InventoryTypeSelect.vue'
import WarehouseSelect from '../../public/views/componentsWeb/WarehouseSelect.vue'
import DateTimeSelect from '../../public/views/componentsWeb/DateTimeSelect.vue'
import EmployeeSelect from '../../public/views/componentsWeb/EmployeeSelect.vue'
import QualityInputCell from '../../public/views/componentsWeb/QualityInputCell.vue'
import SinglePriceInputCell from '../../public/views/componentsWeb/SinglePriceInputCell.vue'
import TotalPriceInputCell from '../../public/views/componentsWeb/TotalPriceInputCell.vue'
import SubcommoditySelectDialog from '../../views/inventory/subcommoditySelectDialog.vue'
import BottomBar from '../../public/views/componentsWeb/BottomBar.vue'
import EventBus from '../../public/engine/ipc/eventBus'
import TabUtil from '@/plugins/tab'
import { MessageUtil } from '@/utils/MessageUtil'
import { CopyDocument } from '@element-plus/icons-vue'


export default {
    name: 'InventoryDetailPage',
    components: {
        InputWidgetWeb,
        PartnerSelect,
        InventoryTypeSelect,
        WarehouseSelect,
        DateTimeSelect,
        EmployeeSelect,
        QualityInputCell,
        SinglePriceInputCell,
        TotalPriceInputCell,
        SubcommoditySelectDialog,
        BottomBar
    },

    data() {
        return {
            inventory: Inventory.empty({
                inOutType: InventoryInOutType.In,
                operator: Engine.profile?.nickName,
                operatorId: Engine.profile?.id
            }),

            orgInventory: Inventory.empty({
                inOutType: InventoryInOutType.In,
                operator: Engine.profile?.nickName,
                operatorId: Engine.profile?.id
            }),
            basicUiAction: new BasicUiAction(),
            inventoryUiAction: new InventoryUiAction(),
            enterpriseMgtUiAction: new EnterpriseMgtUiAction(),
            loading: false,
            CommonOrderStatus,
            InventoryInOutType,

            editMode: false,

            inOutType: InventoryInOutType.In, // 默认是入库
            inventoryId: "",

            formData: {
                docCode: '',
                title: '',
                targetObject: null, // 往来单位 targetObject
                inventoryType: null, // InventoryType
                warehouse: null, // 仓库 Warehouse
                operateDate: null, // 出入库时间 Date 对象
                operator: null, // 经办人 Employee 类型
                remark: '',

                updator: null,
                docMaker: null,
            },

            // 返回数据
            retValue: null,

            selectedCommodities: [],
            submitting: false, // 添加提交状态标识
        }
    },
    mounted() {
        this.retValue = null;
        this.inventoryId = (this.$route.params.id || this.$route.query.id) || "";

        let inoutParam = (this.$route.params.inOutType || this.$route.query.inOutType) || "";
        if (inoutParam == InventoryInOutType.In.toString()) {
            this.inOutType = InventoryInOutType.In;
        }
        else if (inoutParam == InventoryInOutType.Out.toString()) {
            this.inOutType = InventoryInOutType.Out;
        }

        //console.log("inventory detail page inoutType:", this.inOutType);


        if (this.inOutType == InventoryInOutType.Out) {
            // 默认初始化时入库单，如果时出库单则需要重新初始化
            this.inventory = Inventory.empty({
                inOutType: InventoryInOutType.Out,
                operator: Engine.profile?.nickName,
                operatorId: Engine.profile?.id
            });

            this.orgInventory = Inventory.empty({
                inOutType: InventoryInOutType.Out,
                operator: Engine.profile?.nickName,
                operatorId: Engine.profile?.id
            });

        }

        if (!Util.isEmpty(this.inventoryId)) {
            this.loadInventoryData();
        }
        else {
            this.editMode = true;
            this.syncFormData();
        }
    },
    // 卸载页面
    beforeUnmount() {
        // console.log('---> commodityDetailPage beforeUnmount');
        if (this.retValue) {
            EventBus.emit('inventoryUpdated', null);
            this.retValue = null;
        }
    },

    // 页面被隐藏时触发
    deactivated() {
        // console.log('---> commodityDetailPage deactivated');
        if (this.retValue) {
            EventBus.emit('inventoryUpdated', null)
            this.retValue = null;
        }
    },

    computed: {

        initPartnerCode() {
            let code = this.inOutType == InventoryInOutType.In ? 'supplier' : 'customer';
            console.log('initPartnerCode', code);
            return code;
        },
        latestUpdateInfo() {
            return (this.inventory.updateor && this.inventory.updateDate) ?
                (this.inventory.updateor + "  " + DateUtil.getDayTitle(this.inventory.updateDate)) : null;
        },

        docMaker() {
            return (this.inventory.id && this.inventory.docMaker && this.inventory.recordDate) ?
                (this.inventory.docMaker + "  " + DateUtil.getDayTitle(this.inventory.recordDate)) : null
        },

        docMakerBottmBar() {
            return Engine.profile?.nickName.isEmpty
                ? Engine.profile?.userName
                : Engine.profile?.nickName;
        },

        inoutTypeLabel() {
            return this.inOutType == InventoryInOutType.In ? '入库类型' : '出库类型'
        },

        operationTimeLabel() {
            return this.inOutType == InventoryInOutType.In ? '入库时间' : '出库时间'
        },

        commodityGroupTitle() {
            return this.inOutType == InventoryInOutType.In ? '入库商品' : '出库商品'
        }


    },

    methods: {

        syncFormData() {

            this.formData = {
                docCode: this.inventory.docCode,
                title: this.inventory.title,
                targetObject: this.inventory.targetObject,
                //  inventoryType: Util.isEmpty(this.inventory.type.id) ? null: this.inventory.type,
                inventoryType: this.inventory.type,
                warehouse: this.inventory.wareHouse,
                operateDate: this.inventory.operateDate,
                operator: new Employee({ id: this.inventory.operatorId, name: this.inventory.operator }),
                remark: this.inventory.remark,

                //
                updator: (this.inventory.updateor && this.inventory.updateDate) ?
                    (this.inventory.updateor + "  " + DateUtil.getDayTitle(this.inventory.updateDate)) : null,
                docMaker: (this.inventory.id && this.inventory.docMaker && this.inventory.recordDate) ?
                    (this.inventory.docMaker + "  " + DateUtil.getDayTitle(this.inventory.recordDate)) : null,
            }
        },

        fillWithFormData() {
            this.inventory.title = this.formData.title
            this.inventory.targetObject = this.formData.targetObject
            this.inventory.type = this.formData.inventoryType
            this.inventory.wareHouse = this.formData.warehouse

            // formData.operateDate 控件变更日期会转换为字符串，这里需要转换回Date对象
            if (!(this.formData.operateDate instanceof Date)) {
                this.inventory.operateDate = DateUtil.strToDate(this.formData.operateDate);
            } else {
                this.inventory.operateDate = this.formData.operateDate;
            }
            this.inventory.setOperator({ operator: this.formData.operator.name, operatorId: this.formData.operator.id })
            this.inventory.remark = this.formData.remark
        },

        // 商品选择 items 类型 SubCommodityInventorySumData
        handleCommoditySelect(items) {
            //console.log('handleCommoditySelect:', items);

            if (items && items.length > 0) {
                for (let commodity of items) {
                    let batchIn = new CommodityBatch({
                        commodity: commodity.subCommodity,
                        availableCount: commodity.availableCount,
                        inventoryCount: commodity.totalInventoryCount,
                        count: new CsDouble(1),
                        batchPrice: commodity.subCommodity.retailPrice,
                        singlePrice: commodity.subCommodity.retailPrice
                    });
                    this.inventory.addCommodityBatch(batchIn);
                }
            }
        },


        handleCopy() {
            this.inventory = Inventory.clone(this.inventory)
            this.inventory.id = ''
            this.editMode = true;
            MessageUtil.showSuccessMsg("复制完成");
        },

        handlePrint() { },
        handleEdit() {
            this.editMode = true
        },
        async handleDelete() {
            if (Util.isEmpty(this.inventory.id)) {
                TabUtil.closePage();
            }
            else {

                try {
                    const orderTitle = this.inOutType == InventoryInOutType.In ? '入库单' : '出库单';
                    // console.log('删除出入库单据');
                    await ElMessageBox.confirm("确定要删除该" + orderTitle + "据吗？", "删除确认", {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    });

                    this.submitting = true;

                    let delResult = await this.inventoryUiAction.removeInventoryOrder({
                        orderId: this.inventory.id,
                        docType: this.inventory.docType
                    });
                    if (delResult == null) {
                        this.retValue = new ActionResult({ type: ActionResultType.Del })
                        MessageUtil.showSuccessMsg("删除成功");
                        TabUtil.closePage();
                    }
                }
                catch (error) {
                    if (error !== 'cancel') {
                        console.error("inventoryDetailPage handleDelete error:", error);
                        ElMessage.error("删除操作失败");
                    }
                }
                finally {
                    this.submitting = false;
                }
            }
        },

        //// 商品选择

        handleAddCommodity() {
            let currentCommodityList = this.inventory.commmodityList;
            this.$refs.commoditySelectDialog.open(currentCommodityList);
        },

        handleSelectionChange(selection) {
            this.selectedCommodities = selection;
        },
        handleDeleteSelectedCommodities() {
            if (this.selectedCommodities.length === 0) {
                ElMessage.warning('请至少选择一个商品进行删除');
                return;
            }

            // 删除选中的商品
            this.inventory.updateCommodityList(this.inventory.commmodityList.filter(
                item => !this.selectedCommodities.includes(item)
            ));

            // 清空选中
            this.selectedCommodities = [];
        },
        //// 商品单位，数量编辑
        handlePriceChange(row) {
            this.updateBatchPrice(row);
        },
        handleCountChange(row) {
            this.updateBatchPrice(row);
        },
        updateBatchPrice(row) {
            row.batchPrice.value = row.singlePrice.value * row.count.value;
            this.updateTotal();
        },
        updateTotal() {
            const total = this.inventory.commmodityList.reduce((sum, item) => sum + item.batchPrice.value, 0);
            this.inventory.inventoryFundMount.value = total;
            this.inventory.totalCount.value = this.inventory.commmodityList.reduce((sum, item) => sum + item.count.value, 0);
        },

        // 取消编辑
        handleCancel() {

            this.inventory = Inventory.clone(this.orgInventory);

            this.editMode = false;

        },
        async handleSubmit() {
            this.submitting = true;
            try {
                // First validate the form
                await this.$refs.ruleFormRef.validate();

                // 延时测试
                /*
                await new Promise((resolve) => {
                    setTimeout(() => {
                        resolve();
                    }, 3000);
                });
                return;
                */

                if (this.inventory.commmodityList.length <= 0) {
                    ElMessage.warning("请选择商品!");
                    return;
                }

                this.fillWithFormData();
                // console.log('提交出入库单数据 formData', this.formData);
                console.log('提交出入库单数据', this.inventory);
                await this.submitInventoryData();
            } catch (error) {
                console.error('表单验证失败', error);
                ElMessage.error("单据信息不完全!");
                return;
            } finally {
                this.submitting = false;
            }
        },

        /// 是否保存并审核     bool toAudit
        async submitInventoryData(toAudit = true) {
            // 返回的 OrderResult 对象
            const orderResult = await this.inventoryUiAction.updateOrCreateInventoryBatch(this.inventory, toAudit)

            if (orderResult) {
                if (Util.isEmpty(this.inventory.id)) {
                    this.retValue = new ActionResult({ type: ActionResultType.New })
                }
                else {
                    this.retValue = new ActionResult({ type: ActionResultType.UpdateCommon })
                }
            }

            if (orderResult) {
                // 刷新订单页面
                ElMessage.success("提交保存成功");

                this.inventoryId = orderResult.id;
                this.editMode = false;
                this.loadInventoryData();
            }
        },
        //////////////////// 
        async loadInventoryData() {
            try {
                this.loading = true

                const res = await this.inventoryUiAction.getInventoryDetailInfo(this.inventoryId)

                if (res) {
                    this.inventory = res;
                    this.orgInventory = Inventory.clone(res);
                    this.syncFormData();
                } else {
                    ElMessage.error('获取出入库单详情失败')
                }
            } catch (error) {
                console.error('加载出入库单数据失败:', error)
                ElMessage.error('加载出入库单数据失败')
            } finally {
                this.loading = false
            }
        },

        formatCurrency(value) {
            return Util.getFundString(value);
        },

        formatCount(value) {
            return Util.getCountString(value);
        },

        formatDateTime(dateStr) {
            if (!dateStr) return ''
            return DateUtil.formatDate(dateStr, 'yyyy-MM-dd HH:mm:ss')
        },
    }
}
</script>

<style scoped>
.inventory-detail-container {
    padding: 16px;
    padding-bottom: 80px;
    /* 留出bottom bar的空间 */
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.action-buttons {
    display: flex;
    gap: 12px;
    margin-bottom: 0px;
    padding: 0 16px;
}

/* 在现有样式中添加或修改 */
.title-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
}

.summary-container {
    flex: 1;
    min-width: 300px;
    /* 根据实际需要调整宽度 */
    display: flex;
    align-items: center;
    gap: 12px;
}

.total-info {
    color: #606266;
    font-size: 14px;
    white-space: nowrap;
    /* 防止换行 */
}

.store-name {
    font-size: 12px;
    color: #606266;
}

.title-text {
    font-size: 16px;
    font-weight: bold;
}

.status-tag {
    margin-left: 12px;
}

.total-info {
    color: #606266;
    font-size: 14px;
}

.commodity-info {
    display: flex;
    align-items: center;
}

.commodity-image {
    width: 40px;
    height: 40px;
    margin-right: 12px;
}

.commodity-text {
    display: flex;
    flex-direction: column;
}

.commodity-name {
    font-weight: 500;
    margin-bottom: 4px;
}

.commodity-spec {
    font-size: 12px;
    color: #909399;
}

.remark-content {
    white-space: pre-wrap;
    word-break: break-all;
}

.info-card,
.items-card,
.other-info-card {
    margin-bottom: 16px;
    border-radius: 8px;
}
</style>